package com.ruyuan.engine.service;

import com.ruyuan.engine.pojo.ClientLog;
import com.ruyuan.engine.pojo.RuleComplexParam;
import com.ruyuan.engine.pojo.RuleEventExecuteParam;
import com.ruyuan.engine.utils.RuleCommonProcessUtils;
import org.apache.flink.api.common.state.ListState;

import java.util.List;

/**
 * 组合事顺序类条件封装
 * */
public class SequenceRuleServiceImpl implements SequenceRuleService {

    ListState<ClientLog> clientLogListState;

    public SequenceRuleServiceImpl(ListState<ClientLog> listState) {
        this.clientLogListState = listState;
    }

    @Override
    public boolean mathRuleSequenceCount(ListState<ClientLog> clientLogListState, RuleComplexParam ruleComplexParam) {
        try {
            Iterable<ClientLog> clientLogs = clientLogListState.get();
            //顺序规则
            List<RuleEventExecuteParam> sequenceRuleParams = ruleComplexParam.getSequenceRuleParams();
            //返回最后匹配到的规则
            int lastStep = matchRuleComplexMaxStep(clientLogs,sequenceRuleParams);
            ruleComplexParam.setSequenceRuleLastStep(ruleComplexParam.getSequenceRuleLastStep()+lastStep);
            //最后的步骤和规则的数量进行比较，得到返回值
            return lastStep == ruleComplexParam.getSequenceRuleParams().size();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean mathRuleSequenceCount(RuleComplexParam ruleComplexParam) {
        return mathRuleSequenceCount(clientLogListState,ruleComplexParam);
    }

    @Override
    public boolean mathRuleSequenceCount(ClientLog clientLog, RuleComplexParam ruleComplexParam) {
        return mathRuleSequenceCount(ruleComplexParam);
    }

    /**
     * 规则匹配的核心逻辑
     * */
    public int matchRuleComplexMaxStep(Iterable<ClientLog> clientLogs, List<RuleEventExecuteParam> sequenceRuleParams) {
        int lastStep = 0;
        for (ClientLog log:clientLogs) {
            if (RuleCommonProcessUtils.eventMatchRuleParam(log,sequenceRuleParams.get(lastStep))) {
                lastStep++;
            }
            //什么时候结束呢？ 规则什么时候遍历完就什么时候返回
            if (lastStep == sequenceRuleParams.size()) break;
        }
        return lastStep;
    }
}
